package com.ktc.qa.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private Environment env;

    @Autowired
    private JwtUtil jwtUtil;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String prefix = env.getProperty("jwt.config.prefix");
        String auth = request.getHeader("auth");
        if (auth != null && auth.startsWith(prefix)) {

            String token = auth.substring(prefix.length());
            Claims claims = jwtUtil.parseJWT(token);

            if (claims.get("role").equals("admin")) {
                request.setAttribute("admin_claims",claims);
            }

            if (claims.get("role").equals("user")) {
                request.setAttribute("user_claims",claims);
            }
        }

        // 不管是什么请求一律放行
        return true;
    }

}